<?php
/**
 * Exceptions Handles.
 * User: zx
 * Date: 2019/7/4
 * Time: 16:36
 */
namespace app\exceptions;

use Exception;
use think\exception\Handle;
use think\exception\ValidateException;
use think\db\exception\ModelNotFoundException;
use think\exception\RouteNotFoundException;
use think\facade\Request;
use think\Response;
use think\response\Redirect;
use think\response\View;

Class Handles extends Handle{

    /**
     * 定义不需要返回的异常类
     * @var array
     */
    protected $ignoreReport = [
        ValidateException::class,
        ModelNotFoundException::class,
        RouteNotFoundException::class
    ];

    public function render(Exception $e)
    {
        if ( (Request::isAjax() || Request::isJson() ) && ( $ajax = $this->isAjax($e) ) instanceof Response ) {
            return $ajax;
        } elseif ( ( $view = $this->view( $e ) ) instanceof View || $view instanceof Redirect ) {
            return $view;
        }

        return parent::render($e); // TODO: Change the autogenerated stub
    }

    private function isAjax( $e )
    {
        if ( $e instanceof OrdinaryException ) {
            return failed($e->getMessage(), $e->getCode()?:500);
        }
        if ( $e instanceof ValidateException ) {
            return failed(is_array($e->getError())?reset($e->getError()):$e->getError(), 422);
        }
        if ( $e instanceof ModelNotFoundException || $e instanceof RouteNotFoundException ) {
            return notFound();
        }
        if ( $e instanceof PowerException ) {
            return power();
        }
        if ( $e instanceof Redirect ) {
            return notLogin();
        }
        return false;
    }

    private function view( $e )
    {
        if ( $e instanceof OrdinaryException ) {
            return view('common@error/error', ['title'=>$e->getCode()?:500, 'message'=>$e->getMessage(), 'code'=>500]);
        }
        if ( $e instanceof ValidateException ) {
            return view('common@error/error', ['title'=>422, 'message'=>is_array($e->getError())?reset($e->getError()):$e->getError(), 'code'=>422]);
        }
        if ( $e instanceof ModelNotFoundException || $e instanceof RouteNotFoundException ) {
            return view('common@error/error');
        }
        if ( $e instanceof PowerException ) {
            return view('common@error/error', ['title'=>401,'message'=>'权限不足', 'code'=>401]);
        }
        if ( $e instanceof RedirectException ) {
            return redirect('/admin/login');
        }
        return false;
    }

}